//
//  SuiJiaoSuiDaoViewController.m
//  XDBaseFrameWork
//
//  Created by XD-XY on 10/17/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "SuiJiaoSuiDaoViewController.h"

#import "CustomPointAnnotation.h"

@interface SuiJiaoSuiDaoViewController ()

@end

@implementation SuiJiaoSuiDaoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    
    locService.delegate  =self;
    [locService startUserLocationService];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
    
    locService.delegate = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.dataArray = [[NSMutableArray alloc] init];
    
    self.titleLabel.text =@"随e拍";
    
    UIButton * rightBtn = [self createButtonOnNavigationWithRect:CGRectMake(UI_SCREEN_WIDTH-80, 0, 80, 44) normalImg:nil highlightImg:nil];
    [rightBtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightBtn setTitle:@"切换列表" forState:UIControlStateNormal];
    [self.navigationBarView addSubview:rightBtn];
    
    //定位
    locService = [[BMKLocationService alloc] init];
    
    //百度地图
    _mapView = [[BMKMapView alloc] initWithFrame:self.contentView.bounds];
    [_mapView setZoomLevel:17];
    [self.contentView addSubview:_mapView];

}

#pragma mark
#pragma mark 切换列表显示
-(void)rightBtnClick
{
    DDLOG_CURRENT_METHOD;
}


#pragma mark 定位Delegate
/**
 *在停止定位后，会调用此函数
 */
- (void)didStopLocatingUser
{
    NSLog(@"停止定位");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    if (latitude>0&&longitude>0){
        [locService stopUserLocationService];
        [XDTools sharedXDTools].latitude = latitude;
        [XDTools sharedXDTools].longitude = longitude;
        
    }
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserLocation:(BMKUserLocation *)userLocation
{
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    if (latitude>0&&longitude>0){
        [locService stopUserLocationService];
        [XDTools sharedXDTools].latitude = latitude;    //经度
        [XDTools sharedXDTools].longitude = longitude;  //纬度
        
        _mapView.centerCoordinate = userLocation.location.coordinate;
        
        [self getDatas];
        
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%f",latitude] forKey:@"latitude"];
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%f",longitude] forKey:@"longitude"];
    }
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

-(void)getDatas
{
    if (![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    NSDictionary * parms = @{@"Lng":[NSString stringWithFormat:@"%f",longitude],
                             @"Lat":[NSString stringWithFormat:@"%f",latitude]};
    
    ASIHTTPRequest * request = [XDTools postRequestWithDict:parms API:API_getEmplByRange];
    
    __weak ASIHTTPRequest * mrequest = request;
    
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            if (ARRAY_IS_NOT_EMPTY(tmpDict[@"data"][@"List"])){
                [_dataArray addObjectsFromArray:tmpDict[@"data"][@"List"]];
                [self relashMapViews];
            }
            
        }else{
            [XDTools showTips:tmpDict[@"msg"] toView:self.view];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
        [XDTools showTips:networkovertime toView:self.view];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}

#pragma mark
#pragma mark 刷新地图显示数据
-(void)relashMapViews
{
    NSMutableArray * pointArray = [[NSMutableArray alloc] init];
    for (NSDictionary * dict in _dataArray){
        BMKPointAnnotation * item = [[BMKPointAnnotation alloc] init];
        item.title = dict[@"EmplName"];
        CLLocationDegrees latitud = [dict[@"CurN"] floatValue];
        CLLocationDegrees longitud = [dict[@"CurE"] floatValue];
        CLLocationCoordinate2D coor;
        coor.latitude = latitud;
        coor.longitude = longitud;
        item.coordinate = coor;
        
        [pointArray addObject:item];
    }
    [_mapView addAnnotations:pointArray];
    
}

#pragma mark -
#pragma mark implement BMKMapViewDelegate
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{

    // 生成重用标示identifier
    NSString * AnnotationViewID = @"xidanMark";
	
    // 检查是否有重用的缓存
    BMKAnnotationView * annotationView = (BMKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
    if (annotationView == nil) {
        
        annotationView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
    }
    
	annotationView.image = [UIImage imageNamed:@"l_icon_green@2x"];
    // 设置位置
	annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
	annotationView.canShowCallout = YES;
    
    // 设置是否可以拖拽
    annotationView.draggable = NO;


//    _mapView.centerCoordinate = annotation.coordinate;

    return annotationView;

}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
